import Vue from 'vue'
import store from '../store'
import VueRouter from 'vue-router'
import { Toast } from 'vant'
import { MainView } from '../components/layouts' //, CardView

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
    component: r => require(['../components/tab-bar'], r),
    children: [
      {
        path: '/home',
        name: 'Home',
        meta: { title: '消费统计' },
        component: () => import('../views/home')
      },
      {
        path: '/nutrition',
        name: 'Nutrition',
        meta: { title: '个人营养报告' },
        component: () => import('../views/nutrition')
      },
      { path: '/order', name: 'Order', meta: { title: '订单查询' }, component: () => import('../views/order') },
      { path: '/mine', name: 'Mine', meta: { title: '我的' }, component: () => import('../views/mine') }
    ]
  },
  {
    path: '/main',
    component: MainView,
    children: [
      { path: '/order/detail', name: 'OrderDetail', meta: { title: '订单详情' }, component: () => import('../views/order-detail') },
      { path: '/recharge/list', name: 'RechargeList', meta: { title: '充值记录' }, component: () => import('../views/recharge-list') },
      { path: '/myqrcode', name: 'MyQrCode', meta: { home: true, title: '我的二维码' }, component: () => import('../views/myqrcode') }
    ]
  },
  {
    path: '/account',
    redirect: '/login',
    component: () => import('../views/account/layout'),
    children: [
      {
        path: '/login',
        name: 'Login',
        meta: { title: '登录', skip: true },
        component: () => import('../views/account/login')
      },
      {
        path: '/register',
        name: 'Register',
        meta: { title: '注册', skip: true },
        component: () => import('../views/account/register')
      }
    ]
  },
  { path: '/error/:state', name: 'Error', meta: { skip: true }, component: () => import('../views/other/error') }, //失败页面
  { path: '*', name: 'All', meta: { skip: true }, redirect: '/error/404' } //含有通配符的路由应该放在最后
]

const router = new VueRouter({ routes })

//全局前置守卫
router.beforeEach((to, from, next) => {
  Toast.loading()
  //已登录 或 跳过登录验证
  if (to.meta?.skip || store.state?.accessToken) next()
  else {
    Toast.clear()
    next({ name: 'Login', replace: true, query: { redirect: to.fullPath } })
  }
})
//全局后置钩子
router.afterEach(() => {
  Toast.clear()
})
export default router
